import os, sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)))

# from flask.ext.script import Manager, Server
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from sqlalchemy import create_engine
from app.models.common.ad import Ad
from app.models.common.adpos import AdPo
from app.models.common.attr import Attr
from app.models.common.log import Log
from app.models.common.type import Type
from app.models.console.admin import Admin
from app.models.console.config import Config
from app.models.console.menu import Menu
from app.models.console.role import Role
from app.models.console.rolepriv import RolePriv
from app.models.console.roleuser import RoleUser
from app.models.console.section import Section
from app.models.content.article import Article
from app.models.content.category import Category
from app.models.user.group import Group
from app.models.user.user import User

from app import create_app
app = create_app()

 # 数据库连接
from app.models.database import db
db.init_app(app)

manager = Manager(app,db)

migrate = Migrate(app, db)

manager.add_command('db', MigrateCommand)

# 数据插入
@manager.option('-f','-file',dest='file',default='dbinit.sql')
def db_insert(file):
    print('Hello',file)
    # Read the sql file
    query = open(file, 'r')
    sqls = query.read().splitlines()
    query.close()
    # list 转 str
    # connection == the connection to your database, in your case prob_db
    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
    con = engine.connect()
    # 要保证所有表是空的
    for i in sqls:
        con.execute(i)
    con.close()
    engine.dispose()
    print('success')

if __name__ == '__main__':
    manager.run()